package com.cy.pj.ajax.controller;

import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
public class AjaxController {

    @RequestMapping("/doAjaxStart")
    public String doAjaxStart() {
        return "ajax-01";
    }

    //=============================================================
    private List<Map<String, Object>> data = new ArrayList<>();

    public AjaxController() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", "100");
        map.put("name", "华为");
        map.put("remark", "very good");
        data.add(map);
    }

    @RequestMapping("/doAjaxGet")
    public List<Map<String, Object>> doAjaxGet() {
        return data;
    }

    @RequestMapping("/doAjaxPost")
    public String doAjaxPost(@RequestParam Map<String, Object> map) {
        data.add(map);
        return "save ok";
    }

    @DeleteMapping("/doAjaxDelete/{id}")
    public String doAjaxDelete(@PathVariable Integer id) {
        System.out.println(id + "ppppppppppppppppppppppppppppppasdffasdf");
        Iterator<Map<String, Object>> it = data.iterator();

        while (it.hasNext()) {
            Map<String, Object> map = it.next();
            String aa = String.valueOf(id);
            if (map.get("id").equals(aa)) {
                it.remove();
            }
        }
        return "delete ok";
    }


    @PutMapping("/doAjaxPut")
    @ResponseBody
    public String doAjaxPut(@RequestParam Map<String, Object> map) {
        String id = (String) map.get("id");
        Iterator<Map<String, Object>> it = data.iterator();
        Map<String, Object> obj = null;
        while (it.hasNext()) {
            obj = it.next();
            if (obj.get("id").equals(id)) break;
        }
        obj.put("name", map.get("name"));
        obj.put("remark", map.get("remark"));
        return "update ok";
    }


}
